package com.chuantou.yuba.ui;

import java.util.HashMap;
import java.util.regex.Matcher;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.SMSSDK;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.LoginTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.StackManager;

/**
 * 注册主界面
 * 
 * @author Administrator
 * 
 */
public class RegistActivity extends BaseActionBarActivity implements OnClickListener {
	private static final String TAG = RegistActivity.class.getName();
	private static final int WHAT_REMOVE_ERROR_MSG = 1;
	private static final int WHAT_COUNT_DOWN = 2;
	private boolean mIsRegist = false;
	private EditText mPhoneView;
	private EditText mVerifyCodeView;
	private TextView mCountDownView;
	private EditText mPassView;
	private TextView mErrorView;
	private ProgressDialog mRegistDialog = null;
	private ProgressDialog mLoginDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist);
		setTitle(R.string.regist);
		setupViews();
	}

	private void setupViews() {
		mPhoneView = (EditText) findViewById(R.id.phone);
		mVerifyCodeView = (EditText) findViewById(R.id.verify_code);
		mPassView = (EditText) findViewById(R.id.password);
		mErrorView = (TextView) findViewById(R.id.message);
		mCountDownView = (TextView) findViewById(R.id.count_down);
		mCountDownView.setOnClickListener(this);
		invalidateSendVerifyCodeTextView();
	}

	private void invalidateSendVerifyCodeTextView() {
		long time = Constants.sLastSendVerifyCodeTime;
		long diff = System.currentTimeMillis() - time;
		if (diff > 60 * 1000) {
			mCountDownView.setEnabled(true);
			mCountDownView.setText(R.string.get_verify_code);
		} else {
			int second = 60 - (int) (diff / 1000);
			mCountDownView.setText(getString(R.string.get_verify_code_after, second));
			mCountDownView.setEnabled(false);
			mHandler.sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.count_down:
			checkPhoneUnique();
			break;
		default:
			break;
		}
	}
	
	private void sendVerifyCode(String phone){
		SMSSDK.initSDK(getApplicationContext(), Constants.MOB_APP_KEY, Constants.MOB_APP_SECRET);
		String[] country = SMSSDK.getCountry(Constants.DEFAULT_COUNTRY_ID);
		String code = country[1];
		SMSSDK.getVerificationCode(code, phone);
		Constants.sLastSendVerifyCodeTime = System.currentTimeMillis();
		invalidateSendVerifyCodeTextView();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_REMOVE_ERROR_MSG:
				mErrorView.setVisibility(View.GONE);
				break;
			case WHAT_COUNT_DOWN:
				if (!hasDestroyed()) {
					invalidateSendVerifyCodeTextView();
				}
				break;
			default:
				break;
			}
		};
	};

	private void showLoginDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			return;
		}
		mLoginDialog = new ProgressDialog(this);
		mLoginDialog.setCancelable(false);
		mLoginDialog.setMessage(getString(R.string.logining));
		mLoginDialog.show();
	}

	private void dismissLoginDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			mLoginDialog.dismiss();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_continue, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_continue: {
			regist();
		}
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void regist() {
		synchronized (TAG) {
			if (mIsRegist) {
				return;
			}
			final String phone = mPhoneView.getText().toString().trim();
			if (TextUtils.isEmpty(phone) || phone.length() != 11) {
				showErrorMessage(getString(R.string.input_phone_error));
				return;
			} else {
				Matcher matcher = Constants.PHONE_PATTERN.matcher(phone);
				if (!matcher.matches()) {
					showErrorMessage(getString(R.string.input_phone_error));
					return;
				}
			}

			final String password = mPassView.getText().toString().trim();
			if (TextUtils.isEmpty(password) || password.length() < 6) {
				showErrorMessage(getString(R.string.input_password_error));
				return;
			}

			final String verifyCode = mVerifyCodeView.getText().toString().trim();
			if (TextUtils.isEmpty(verifyCode)) {
				showErrorMessage(getString(R.string.input_verify_code_error));
				return;
			}

			mIsRegist = true;
			showRegistDialog();
			String registUrl = UriHelper.getRegistByPhoneUrl();
			HashMap<String, String> registParams = new HashMap<String, String>();
			registParams.put(UriHelper.PARAMS_MOBILE, phone);
			registParams.put(UriHelper.PARAMS_CODE, verifyCode);
			registParams.put(UriHelper.PARAMS_PASSWORD, password);

			GsonRequest<BaseTO> registRequest = new GsonRequest<BaseTO>(Method.POST, registUrl, new Listener<BaseTO>() {

				@Override
				public void onResponse(BaseTO response) {
					if (!hasDestroyed()) {
						dismissRegistDialog();
						if (response == null) {
							showErrorMessage(getString(R.string.server_error));
						} else {
							if (response.isSuccess()) {
								login(phone, password);
							} else {
								String msg = response.getMsg();
								msg = TextUtils.isEmpty(msg) ? getString(R.string.regist_error) : msg;
								showErrorMessage(msg);
							}
						}
					}

				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (!hasDestroyed()) {
						dismissRegistDialog();
						showErrorMessage(getString(R.string.request_error));
					}
				}
			}, registParams, BaseTO.class);
			RequestManager.startRequest(getApplicationContext(), registRequest);
		}

	}

	private void login(String phone, String password) {
		String url = UriHelper.getLoginUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_MOBILE, phone);
		params.put(UriHelper.PARAMS_PASSWORD, password);
		BDLocation location = YBApp.get().getLocation();
		if (location != null) {
			params.put(UriHelper.PARAMS_POINT, location.getLongitude() + "," + location.getLatitude());
		}
		showLoginDialog();
		GsonRequest<LoginTO> request = new GsonRequest<LoginTO>(Method.POST, url, new Listener<LoginTO>() {

			@Override
			public void onResponse(LoginTO response) {
				if (!hasDestroyed()) {
					dismissLoginDialog();
					if (response == null) {
						Toast.makeText(getApplicationContext(), R.string.login_failed, Toast.LENGTH_SHORT).show();
					} else {
						if (response.isSuccess()) {
							UserTO user = response.getUser();
							user.setLoginTime(System.currentTimeMillis());
							AccountManager.saveUser(getApplicationContext(), user);
							StackManager.finishAll();
							sendBroadcast(new Intent(Constants.INTENT_ACITON_LOGIN));
							toUpdateProfileActivity();
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? getString(R.string.login_failed) : msg;
							showErrorMessage(msg);
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dismissLoginDialog();
					showErrorMessage(getString(R.string.login_failed));
				}
			}
		}, params, LoginTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private void toUpdateProfileActivity() {
		Intent intent = new Intent(this, UpdateProfileActivity.class);
		startActivity(intent);
		finish();
	}

	private void showErrorMessage(String msg) {
		mHandler.removeMessages(WHAT_REMOVE_ERROR_MSG);
		mErrorView.setVisibility(View.VISIBLE);
		mErrorView.setText(msg);
		mHandler.sendEmptyMessageDelayed(WHAT_REMOVE_ERROR_MSG, 1500);
	}

	private void showRegistDialog() {
		if (mRegistDialog != null && mRegistDialog.isShowing()) {
			return;
		}
		mRegistDialog = new ProgressDialog(this);
		mRegistDialog.setMessage(getString(R.string.submiting));
		mRegistDialog.setCancelable(false);
		mRegistDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				mIsRegist = false;
			}
		});
		mRegistDialog.show();
	}

	private void dismissRegistDialog() {
		if (mRegistDialog != null && mRegistDialog.isShowing()) {
			mRegistDialog.dismiss();
			mRegistDialog = null;
		}
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	/***
	 * 检查手机号码唯一性
	 */
	private void checkPhoneUnique() {
		final String phone = mPhoneView.getText().toString().trim();
		if (TextUtils.isEmpty(phone) || phone.length() != 11) {
			showErrorMessage(getString(R.string.input_phone_error));
			return;
		} else {
			Matcher matcher = Constants.PHONE_PATTERN.matcher(phone);
			if (!matcher.matches()) {
				showErrorMessage(getString(R.string.input_phone_error));
				return;
			}
		}
		showRegistDialog();
		String url = UriHelper.getCheckPhoneUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_MOBILE, phone);
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (!hasDestroyed()) {
					dismissRegistDialog();
					if (response == null) {
						Toast.makeText(getApplicationContext(), R.string.request_verify_code_error, Toast.LENGTH_SHORT).show();
					} else {
						if (response.isSuccess()) {
							sendVerifyCode(phone);
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? getString(R.string.request_verify_code_error) : msg;
							showErrorMessage(msg);
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dismissRegistDialog();
					showErrorMessage(getString(R.string.login_failed));
				}
			}
		}, params, BaseTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}
}
